package it.polimi.swKnights.SWIMv2.ejb.administration;

import it.polimi.swKnights.SWIMv2.ejb.authentication.LoginHandlerLocal;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Admin;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Feedback;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.FeedbackPk;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class DisputedFeebackHandler
 */
@Stateless
public class DisputedFeebackHandler implements DisputedFeebackHandlerRemote
{

	@EJB
	private LoginHandlerLocal loginController;

	@PersistenceContext(unitName = "swimv2-manager")
	private EntityManager managerUC;

	@Override
	public List<Map<String, String>> getListDisputedFeedbacks(String userName,
			String password) throws LoginFailException,
			InvalidLoginPrivilegesException
	{

		try
		{
			loginController.checkLoginDataAndPrivileges(userName, password,
					Admin.class);

			List<Map<String, String>> lstMapFeedbacks = new ArrayList<Map<String, String>>();

			String queryText = "" + "SELECT f " + "FROM Feedback as f "
					+ "WHERE f.disputed=true";
			// + "f.gotBy=:asker";

			Query q = null;
			List<?> queryListFeed = null;

			q = managerUC.createQuery(queryText);
			queryListFeed = q.getResultList();

			for (Object resultArr : queryListFeed)
			{
				Feedback f = (Feedback) resultArr;

				Map<String, String> feedbackData = new HashMap<String, String>();

				feedbackData.put("id", String.valueOf(f.getId()));
				feedbackData.put("got_by", f.getGotByUsername());
				feedbackData.put("title_feedback", f.getText());
				
				if(f.getLeftBy() != null)
				{
					feedbackData.put("left_by", f.getLeftBy().getUserName());
				}
				else
				{
					feedbackData.put("left_by", "cancelled user");
				}
				
				feedbackData.put("rank", String.valueOf(f.getRank()));

				lstMapFeedbacks.add(feedbackData);
			}

			return lstMapFeedbacks;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new LoginFailException();

		}

	}

	@Override
	public void removeFeedback(String idFeed, String gotBy, String admin,
			String password) throws LoginFailException,
			InvalidLoginPrivilegesException
	{

		loginController.checkLoginDataAndPrivileges(admin, password,
				Admin.class);

		FeedbackPk fPk = new FeedbackPk();
		fPk.setGotBy(gotBy);
		fPk.setId(Integer.parseInt(idFeed));

		Feedback f = managerUC.find(Feedback.class, fPk);

		managerUC.remove(f);

	}

}
